package com.zyht.common.util;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Base64Utils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import com.mchange.lang.ByteUtils;
import com.zyht.common.bean.PropertiesUtilBean.PropertiesUtils;

public class UploaderUtils {

	private static Logger logger = LoggerFactory.getLogger(UploaderUtils.class);
	
	public static String upload(String typeFolder, InputStream fileStream, String fileName, HttpServletRequest request) throws IOException{
		String uploadPath = "";
		String configPath = "";
		String useAbsolutly = PropertiesUtils.getConfig("file_upload_use_absoluty_path");
		boolean flag = Boolean.parseBoolean(useAbsolutly);
		if(flag){
			configPath = PropertiesUtils.getConfig("file_upload_sys_dir");
		}else{
			uploadPath = request.getSession().getServletContext().getRealPath("/");
			configPath = PropertiesUtils.getConfig("file_upload_dir");
		}
		
		SimpleDateFormat sf = new SimpleDateFormat("yyyy"+File.separator+"MM"+File.separator+"dd");
		String nowStr = sf.format(new Date());
		String oname = fileName;
		String ext = StringUtils.getFilenameExtension(oname);
		String appendPath = configPath + File.separator + typeFolder + File.separator + nowStr + File.separator + System.currentTimeMillis()
				+ new Random().nextInt(6) + "." +ext;
		String realPath = uploadPath + appendPath;
		File filePath = new File(realPath);	
		try {
			logger.debug("文件["+filePath.getAbsolutePath()+"]开始上传");
			FileUtils.copyInputStreamToFile(fileStream, filePath);
		} catch (IOException e) {
			logger.error("文件["+filePath.getAbsolutePath()+"]上传异常："+e.getMessage());
			throw e;
		}
		logger.debug("文件相对路径是:" + appendPath);
		int port = request.getServerPort();
		String basePath = request.getScheme()+"://"+request.getServerName();
		if(port!=80){
			basePath=basePath+":"+port;
		}
		basePath += request.getContextPath()+"/";
		logger.info("文件路径为：====================="+appendPath);
		appendPath = basePath + "link?path=" + encodeFilePath(appendPath);
		logger.debug("文件["+filePath.getAbsolutePath()+"]上传结束.....");
		return appendPath;
	}
	
	public static String uploadAndReturnApath(String typeFolder, InputStream fileStream, String fileName, HttpServletRequest request) throws IOException{
		String uploadPath = "";
		String configPath = "";
		String useAbsolutly = PropertiesUtils.getConfig("file_upload_use_absoluty_path");
		boolean flag = Boolean.parseBoolean(useAbsolutly);
		if(flag){
			configPath = PropertiesUtils.getConfig("file_upload_sys_dir");
		}else{
			uploadPath = request.getSession().getServletContext().getRealPath("/");
			configPath = PropertiesUtils.getConfig("file_upload_dir");
		}
		
		String oname = fileName;
		String ext = StringUtils.getFilenameExtension(oname);
		String appendPath = configPath + File.separator + typeFolder + File.separator + System.currentTimeMillis()
				+ new Random().nextInt(6) + "." +ext;
		String realPath = uploadPath + appendPath;
		File filePath = new File(realPath);	
		try {
			logger.debug("文件["+filePath.getAbsolutePath()+"]开始上传");
			FileUtils.copyInputStreamToFile(fileStream, filePath);
		} catch (IOException e) {
			logger.error("文件["+filePath.getAbsolutePath()+"]上传异常："+e.getMessage());
			throw e;
		}
		logger.debug("文件相对路径是:" + appendPath);
		logger.debug("文件["+filePath.getAbsolutePath()+"]上传结束.....");
		return encodeFilePath(filePath.getAbsolutePath());
	}
	
	public static String uploadBanner(InputStream fileStream, String fileName, HttpServletRequest request) throws IOException{
		String uploadPath = "";
		String configPath = "";
		String useAbsolutly = PropertiesUtils.getConfig("file_upload_use_absoluty_path");
		boolean flag = Boolean.parseBoolean(useAbsolutly);
		if(flag){
			configPath = PropertiesUtils.getConfig("file_upload_sys_dir");
		}else{
			uploadPath = request.getSession().getServletContext().getRealPath("/");
			configPath = PropertiesUtils.getConfig("file_upload_dir");
		}
		
		//SimpleDateFormat sf = new SimpleDateFormat("yyyy"+File.separator+"MM"+File.separator+"dd");
		//String nowStr = sf.format(new Date());
		//String oname = fileName;
		//String ext = StringUtils.getFilenameExtension(oname);
		String appendPath = configPath + File.separator +"index_banner"+ File.separator + fileName;
		String realPath = uploadPath + appendPath;
		File filePath = new File(realPath);	
		try {
			logger.debug("文件["+filePath.getAbsolutePath()+"]开始上传");
			FileUtils.copyInputStreamToFile(fileStream, filePath);
		} catch (IOException e) {
			logger.error("文件["+filePath.getAbsolutePath()+"]上传异常："+e.getMessage());
			throw e;
		}
		logger.debug("文件相对路径是:" + appendPath);
		int port = request.getServerPort();
		String basePath = request.getScheme()+"://"+request.getServerName();
		if(port!=80){
			basePath=basePath+":"+port;
		}
		basePath += request.getContextPath()+"/";
		appendPath = basePath + "link?path=" + encodeFilePath(appendPath);
		logger.debug("文件["+filePath.getAbsolutePath()+"]上传结束.....");
		return appendPath;
	}
	
	public static void delete(String path,HttpServletRequest request){
		String encodePath = path.substring(path.indexOf("=")+1);
		String decodePath = UploaderUtils.decodeFilePath(encodePath);
		String basePath = request.getSession().getServletContext().getRealPath("/");
		String realPath = basePath + decodePath;
		File file = new File(realPath);
		//路径为文件且不为空则进行删除
		if(file.isFile()&&file.exists()){
			file.delete();
		}
	}
	
	public static String encodeFilePath(String path){
		try {
			byte[] fpath = Base64Utils.encode(path.getBytes("UTF-8"));
			path = ByteUtils.toHexAscii(fpath);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return path;
	}
	
	public static String decodeFilePath(String key){
		byte[] eStr = ByteUtils.fromHexAscii(key);
		byte[] bStr = Base64Utils.decode(eStr);
		String endStr = key;
		try {
			endStr = new String(bStr, "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return endStr;
	}
	
	//返回相对路径与绝对路径，且路径不加密
	public static String[] upload2(String typeFolder, InputStream fileStream, String fileName, HttpServletRequest request) throws IOException{
		String uploadPath = "";
		String configPath = "";
		String useAbsolutly = PropertiesUtils.getConfig("file_upload_use_absoluty_path");
		boolean flag = Boolean.parseBoolean(useAbsolutly);
		if(flag){
			configPath = PropertiesUtils.getConfig("file_upload_sys_dir");
		}else{
			uploadPath = request.getSession().getServletContext().getRealPath("/");
			configPath = PropertiesUtils.getConfig("file_upload_dir");
		}
		
		SimpleDateFormat sf = new SimpleDateFormat("yyyy"+File.separator+"MM"+File.separator+"dd");
		String nowStr = sf.format(new Date());
		String oname = fileName;
		String ext = StringUtils.getFilenameExtension(oname);
		String appendPath = configPath + File.separator + typeFolder + File.separator + nowStr + File.separator + System.currentTimeMillis()
				+ new Random().nextInt(6) + "." +ext;
		String realPath = uploadPath + appendPath;
		File filePath = new File(realPath);	
		try {
			logger.debug("文件["+filePath.getAbsolutePath()+"]开始上传");
			FileUtils.copyInputStreamToFile(fileStream, filePath);
		} catch (IOException e) {
			logger.error("文件["+filePath.getAbsolutePath()+"]上传异常："+e.getMessage());
			throw e;
		}
		logger.debug("文件相对路径是:" + appendPath);
		int port = request.getServerPort();
		String basePath = request.getScheme()+"://"+request.getServerName();
		if(port!=80){
			basePath=basePath+":"+port;
		}
		basePath += request.getContextPath();
		realPath=basePath+appendPath;
		return new String[]{appendPath,realPath};
	}
	
	public static enum FolderType{
		image,video,file
	}
	public static String file_upload_sys_dir = "upload"+File.separator;
	public static SimpleDateFormat sf = new SimpleDateFormat("yyyy"+File.separator+"MM"+File.separator+"dd");
	/**
	 * 
	 * @param folderType 文件
	 * @param fileStream 
	 * @param fileName
	 * @return String[0]-相对地址 String[1]-绝对地址 null-异常
	 * @throws IOException
	 */
	public static String[] upload3(FolderType folderType, InputStream fileStream, String fileName){
		try {
			String uploadPath = FileUtil.getWebAppPath();
			String nowStr = sf.format(new Date());
			String oname = fileName;
			String ext = StringUtils.getFilenameExtension(oname);
			String appendPath = file_upload_sys_dir + folderType.name() + File.separator + nowStr + File.separator + System.currentTimeMillis()+ new Random().nextInt(6) + "." +ext;
			String realPath = uploadPath + appendPath;
			if(FileUtil.checkBak(realPath)){
			}
			File filePath = new File(realPath);	
			try {
				logger.debug("文件["+filePath.getAbsolutePath()+"]开始上传");
				FileUtils.copyInputStreamToFile(fileStream, filePath);
			} catch (IOException e) {
				logger.error("文件["+filePath.getAbsolutePath()+"]上传异常："+e.getMessage());
				throw e;
			}
			logger.debug("文件相对路径是:" + appendPath);
			return new String[]{appendPath,realPath};
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static String[] randomFilePath(String fileName){
		String uploadPath = FileUtil.getWebAppPath();
		String nowStr = sf.format(new Date());
		String ext = StringUtils.getFilenameExtension(fileName);
		String appendPath = file_upload_sys_dir + FolderType.image + File.separator + nowStr + File.separator + System.currentTimeMillis()+ new Random().nextInt(6) + "." +ext;
		String realPath = uploadPath + appendPath;
		return new String[]{appendPath,realPath};
	}

	/**
	 * 
	 * @param picture
	 * @return String[0]-相对地址 String[1]-绝对地址 null-异常
	 */
	public static String[] uploadImg(MultipartFile picture) {
		String[] fileTypeStr = { "image/x-png","image/pjpeg","image/jpeg","image/bmp","image/png"};
		String type = picture.getContentType();
		logger.debug("文件上传类型是：" + type);
		String[] appendPath =  null;
		for(String str : fileTypeStr){
			if(type.indexOf(str)!=-1){
				try {
					appendPath = upload3(FolderType.image, picture.getInputStream(), picture.getOriginalFilename());
				} catch (IOException e) {
					e.printStackTrace();
					break;
				}
			}
		}
		return appendPath;
	}
}
